#gx的文件，没有需要自己创建
#gx <-'ZB'
#uuid_data<-'test20220317'
#source("/apps/R/rgxzl/R_PROJECT/touliao/std/factor_rule.R",encoding = "UTF-8")
#factor_rule(gx,uuid_data)
factor_rule<-function(gx,uuid_data,REC_REVISE_TIME){
  library(sqldf)
  library('tidyverse')#no
  library(rpart)
  library(rpart.plot)#no
  library(forecast)#no
  library(RJDBC)
  library("xgboost")#no
  library("Matrix")#no
  library("stringr")#no
  library('Cairo')
  load(sprintf("/apps/R/rgxzl/R_PROJECT/touliao/std/Rdata_save/%s/MODEL_DF_%s.RDATA",gx,uuid_data))
  
  equal_dir<-"/apps/R/rgxzl/R_PROJECT/touliao/std/analysis_data/"
  save_dir0<- "/apps/R/rgxzl/R_PROJECT/touliao/std/analysis_data/"
  if(!dir.exists(equal_dir)){
    dir.create(equal_dir,recursive = TRUE)
  }
  if(!dir.exists(save_dir0)){
    dir.create(save_dir0,recursive = TRUE)
  }
  
  
  #print(save_dir0)
  WHOLE_BACKLOG_CODE<-unique(MODEL_DF$WHOLE_BACKLOG_CODE)
  #print(WHOLE_BACKLOG_CODE)
  #PRE_UNIT_CODES<-unique(MODEL_DF$PRE_UNIT_CODE)
  ################用工序代码找数据，然后用unit_code存储
  
  #gxzl在用ODBC64位时访问不了，改用JDBC访问gxzl
  
  drv<-JDBC("com.ibm.db2.jcc.DB2Driver","/apps/R/rgxzl/R_PROJECT/touliao/db2jcc.jar",identifier.quote="\"")
  dbaddress_para <- c("jdbc:db2://10.70.8.53:50053/dbprod4q","gxzl","Gxz1#686")
  gxzl <- dbConnect(drv, dbaddress_para[1],dbaddress_para[2],dbaddress_para[3])
  
  
  merge_df <- sqldf("select * from merge_df where is_used = '1'")
  
  for(WHOLE_BACKLOG_CODE in WHOLE_BACKLOG_CODE){
    print(WHOLE_BACKLOG_CODE)
    # PRE_UNIT_CODE <- 'C309'
    MODEL_UNIT_DF<-MODEL_DF[MODEL_DF$WHOLE_BACKLOG_CODE==WHOLE_BACKLOG_CODE,]
    PRE_UNIT_CODE <- unique(MODEL_DF[grep(sprintf('%s',WHOLE_BACKLOG_CODE),MODEL_DF$WHOLE_BACKLOG_CODE),'PRE_UNIT_CODE'])
    print(PRE_UNIT_CODE)
    source("/apps/R/rgxzl/R_PROJECT/touliao/std/source_fun.R",encoding = "UTF-8")
    NA_all_name<-NA_all_fun(MODEL_UNIT_DF)
    unique_names <- unique_var_fun(MODEL_UNIT_DF)
    
    equal_del<-equal_var_fun(MODEL_UNIT_DF,name=names(MODEL_UNIT_DF),save_dir=equal_dir,save_name=sprintf('%s_equal',PRE_UNIT_CODE))
    
    #剔除掉了唯一的值
    MODEL_UNIT_DF <- subset(MODEL_UNIT_DF,select = setdiff(names(MODEL_UNIT_DF),c(NA_all_name,as.character( unique_names$var_names),equal_del)))
    dim(MODEL_UNIT_DF)
    
    
    
    ct <- rpart.control(xval=10, minsplit=100, cp=0.0001)
    TRAIN_df<-MODEL_UNIT_DF
    
    TRAIN_df[,c("TEMP_ID","IN_WT_SUM","OUT_WT_SUM")]<-NULL
    #如果影响因素没有x值，输出
    
    if(dim(TRAIN_df)[2]!=1&dim(TRAIN_df)[2]!=0){
      
      fit <- rpart(SCRAP_YIELD_RATE ~ .,data=TRAIN_df, control=ct ,method="anova")
      save_dir0<- save_dir0
      save_dir<-sprintf('%s%s/',save_dir0,WHOLE_BACKLOG_CODE)
      print(save_dir)
      if(!dir.exists(save_dir)){
        dir.create(save_dir,recursive = TRUE)
      }
      setwd(save_dir)
      opt<-which.min(fit$cptable[,"xerror"])
      cp<-fit$cptable[opt,"CP"]
      fit_prune<-fit
      
      pred<-predict(fit_prune,newdata = TRAIN_df)
      acc<-accuracy(pred,TRAIN_df[,"SCRAP_YIELD_RATE"])
      RMSE=acc["Test set","RMSE"]
      if(grepl("<",fit_prune$frame$var[1])){
        save_name<-"leaf"
      }else{
        save_name<- paste0(as.character(fit_prune$frame$var[1]),"_minxerror_",RMSE) 
      }
      list.rules.rpart(fit_prune,save_name = save_name,dir_name = save_dir)
      fit_prune$variable.importance
      imp_result<-data.frame(colnames=names(fit_prune$variable.importance),important=fit_prune$variable.importance)
      #write.csv(imp_result,"imp_result_fit_prune.csv",row.names = F)
      if(!identical(data.frame(), imp_result)){
        print(imp_result)
        
        ######存储到数据库中的格式更改
        
        new_a <- separate(data = imp_result,col = colnames,into=c('TABLE_NAME','ENG_FIELD'),sep = '__',remove = FALSE)
        new_a$TABLE_NAME <- paste('T_ODS_',new_a$TABLE_NAME,sep = '')
        #可能包含TOM01__PSR8__8_10，ENGF_FIELD是PSR8，改成PSR
        new_a[grep('PSR',new_a$ENG_FIELD),'ENG_FIELD']<- 'PSR'
        
        
        new_a$whole_backlog_code <- WHOLE_BACKLOG_CODE
        new_a <-sqldf(
          #通过table_name,得到schema_name,通过eng_field得到cn_field
          "   select distinct c.*,d.CN_FIELD,d.is_used from (
                select distinct b.*,a.schema_name from new_a b 
                left join merge_df a on a.table_name = b.table_name)c 
                left join merge_df d on d.ENG_FIELD = c.ENG_FIELD")
        new_a$IMP_SORT <- seq(1:nrow(new_a))
        new_a[grep('ORDER_UNIT_RANGE_WT',new_a$ENG_FIELD),'CN_FIELD']<- '订货重量单件范围'
        new_a[grep('ORDER_UNIT_RANGE_WT',new_a$ENG_FIELD),'IS_USED']<- '1'
        new_a[grep('ORDER_UNIT_DIFF',new_a$ENG_FIELD),'CN_FIELD']<-'订货重量单件差值'
        new_a[grep('ORDER_UNIT_DIFF',new_a$ENG_FIELD),'IS_USED']<- '1'
        new_a$BACKLOG_POS <- unique(merge_df[grep(sprintf('%s',WHOLE_BACKLOG_CODE),merge_df$WHOLE_PROCESS_CODE),'BACKLOG_POS'])
        new_a$UNIT_CODE <- PRE_UNIT_CODE
        
        colnames(new_a) <- toupper(names(new_a))
        new_a$ENG_FIELD <- str_split_fixed(new_a$COLNAMES, "__", 2)[,2]
      }
      else {new_a <- data.frame(WHOLE_BACKLOG_CODE = WHOLE_BACKLOG_CODE,
                                UNIT_CODE = PRE_UNIT_CODE,
                                SCHEMA_NAME ='',TABLE_NAME.x='',
                                imp_result='',ENG_FIELD.y='',
                                CN_FIELD='',IMP_SORT='',IMPORTANT='',
                                IS_USED='',BACKLOG_POS='')}}
    else {
      imp_result <- data.frame()
      new_a <- data.frame(WHOLE_BACKLOG_CODE = WHOLE_BACKLOG_CODE,
                          UNIT_CODE = PRE_UNIT_CODE,
                          SCHEMA_NAME ='',TABLE_NAME.x='',
                          imp_result='',ENG_FIELD.y='',
                          CN_FIELD='',IMP_SORT='',IMPORTANT='',
                          IS_USED='',BACKLOG_POS='')
    }
    
    
    new_a$REC_REVISE_TIME <- REC_REVISE_TIME
    print(new_a)
    save_dir2<-sprintf('%s%s/',save_dir,'result2')
    if(!dir.exists(save_dir2)){
      dir.create(save_dir2,recursive = TRUE)}
    
    write.csv(new_a,paste(save_dir2,WHOLE_BACKLOG_CODE,'_IMPC.csv',sep=''),row.names = F)
    
    dbSendUpdate(gxzl,"INSERT INTO gxzl.T_STD_DEVOTE_COEFF_IMPC_RESULT VALUES (?,?,?,?,?,?,?,?,?,?,?)",new_a$WHOLE_BACKLOG_CODE,new_a$UNIT_CODE,new_a$SCHEMA_NAME,new_a$TABLE_NAME,new_a$ENG_FIELD,new_a$CN_FIELD,new_a$IMP_SORT,new_a$IMPORTANT,new_a$IS_USED,new_a$REC_REVISE_TIME,new_a$BACKLOG_POS)
    
    
    
    
    
    
    
    
    if(!identical(data.frame(), imp_result)){
      imp_len<-ifelse(length(imp_result$colnames)>=10,10,length(imp_result$colnames))
      TRAIN_df<-MODEL_UNIT_DF[,c(as.character(imp_result$colnames)[1:imp_len],"SCRAP_YIELD_RATE")]
      
      col_names<-names(TRAIN_df)
      for(i in col_names){
        if(class(TRAIN_df[,i])!="numeric" ){
          TRAIN_df[is.na(TRAIN_df[,i]),i]<-'NA'
          TRAIN_df[,i]<-as.factor(TRAIN_df[,i])
        }
      }
      sparse_matrix <- sparse.model.matrix(SCRAP_YIELD_RATE~.-1, data = TRAIN_df)
      output_vector = TRAIN_df[,"SCRAP_YIELD_RATE"]
      bst <- xgboost(data = sparse_matrix, missing = NA,label = output_vector,nrounds = 10)
      importance <- xgb.importance(sparse_matrix@Dimnames[[2]], model = bst)
      head(importance)
      importanceRaw <- xgb.importance(sparse_matrix@Dimnames[[2]], model = bst, data = sparse_matrix, label = output_vector)
      importanceClean <- importanceRaw[,`:=`(Cover=NULL, Frequence=NULL)]  #同时去掉cover frequence
      head(importanceClean)
      write.csv(importanceRaw,"xgboost_Importance.csv")
      Feature_names<-importanceRaw$Feature
      #########因为原字段处理后会有NA值，需要将有NA值的字段摘出来后续replace成 字段 =/!= '' or 字段 is(not) null
      ziduan <- list()
      for(i in Feature_names){
        if(grepl("NA",i)){
          ziduan[i] <-str_replace_all(str_split_fixed(i, "__", 2)[,2],'NA' ,"")
        }
      }
      
      col_names<-names(MODEL_UNIT_DF)
      MODEL_UNIT_DF_SP<-MODEL_UNIT_DF
      for(i in col_names){
        if((class(MODEL_UNIT_DF_SP[,i])!="numeric")&(anyNA(MODEL_UNIT_DF_SP[,i])) ){
          MODEL_UNIT_DF_SP[is.na(MODEL_UNIT_DF_SP[,i]),i]<-'NA'
        }
      }
      for(i in col_names){
        if(any(grepl(i,Feature_names))){
          GREPL_NAMES<-Feature_names[grepl(i,Feature_names)]
          SP_names<-unlist(strsplit(GREPL_NAMES,i))
          SP_names<-SP_names[SP_names!=""]
          SP_names<-SP_names[SP_names%in%MODEL_UNIT_DF_SP[,i]]
          for (SP in SP_names) {
            NEW_NAME<-paste0(i,"__",SP)
            MODEL_UNIT_DF_SP[,NEW_NAME]<-ifelse(MODEL_UNIT_DF_SP[,i]==SP,1,0)
          }
        }
      }
      MODEL_UNIT_DF_SPWT<-MODEL_UNIT_DF_SP
      del_names<-setdiff(col_names,Feature_names)
      del_names<-setdiff(del_names,"SCRAP_YIELD_RATE")
      MODEL_UNIT_DF_SP[,del_names]<-NULL
      
      source("/apps/R/rgxzl/R_PROJECT/touliao/std/source_fun.R",encoding = "UTF-8")
      ct <- rpart.control(xval=10, minsplit=100, minbucket=100,cp=0.001) 
      fit <- rpart(SCRAP_YIELD_RATE ~ .,data=MODEL_UNIT_DF_SP, control=ct ,method="anova")
      save_dir1<-sprintf('%s%s/',save_dir,'result1')
      if(!dir.exists(save_dir1)){
        dir.create(save_dir1,recursive = TRUE)
      }
      setwd(save_dir1)
      opt<-which.min(fit$cptable[,"xerror"])
      cp<-fit$cptable[opt,"CP"]
      fit_prune<-fit
      pred<-predict(fit_prune,newdata = MODEL_UNIT_DF_SP)
      acc<-accuracy(pred,MODEL_UNIT_DF_SP[,"SCRAP_YIELD_RATE"])
      RMSE=acc["Test set","RMSE"]
      
      if(grepl("<",fit_prune$frame$var[1])){
        ct <- rpart.control(xval=10, minsplit=100, minbucket=100,cp=0.0001) 
        fit <- rpart(SCRAP_YIELD_RATE ~ .,data=MODEL_UNIT_DF_SP, control=ct ,method="anova")
        save_dir1<-sprintf('%s%s/',save_dir,'result1')
        if(!dir.exists(save_dir1)){
          dir.create(save_dir1,recursive = TRUE)
        }
        setwd(save_dir1)
        opt<-which.min(fit$cptable[,"xerror"])
        cp<-fit$cptable[opt,"CP"]
        fit_prune<-fit
        pred<-predict(fit_prune,newdata = MODEL_UNIT_DF_SP)
        acc<-accuracy(pred,MODEL_UNIT_DF_SP[,"SCRAP_YIELD_RATE"])
        RMSE=acc["Test set","RMSE"]
        save_name<- paste0(as.character(fit_prune$frame$var[1]),"_minxerror_",RMSE) 
        if (grepl("<",fit_prune$frame$var[1])){
          save_name<-"leaf"
        }
        else{
          save_name<- paste0(as.character(fit_prune$frame$var[1]),"_minxerror_",RMSE)  
        }
      }else{
        save_name<- paste0(as.character(fit_prune$frame$var[1]),"_minxerror_",RMSE)  
      }
      
      
      list.rules.rpart(fit_prune,save_name = save_name,dir_name = save_dir1)
      imp_result<-data.frame(colnames=names(fit_prune$variable.importance),important=fit_prune$variable.importance)
      setwd(save_dir1)
      #write.csv(imp_result,"imp_result_fit_prune.csv",row.names = F)
      
      #save_name<-"TOM01__SG_SIGN__TDC51DZC5_minxerror_0.0229716813461575"
      rule_df<- decision_path(tree_model=fit_prune,df=MODEL_UNIT_DF_SPWT,save_name,save_path=save_dir1)
      ct <- rpart.control(xval=10, minsplit=100, minbucket=100,cp=0.0005) 
      fit1 <- rpart(SCRAP_YIELD_RATE ~ .,data=MODEL_UNIT_DF_SP, control=ct ,method="anova")
      opt<-which.min(fit1$cptable[,"xerror"])
      cp<-fit1$cptable[opt,"CP"]
      fit_prune1<-fit1
      pred<-predict(fit_prune1,newdata = MODEL_UNIT_DF_SP)
      acc<-accuracy(pred,MODEL_UNIT_DF_SP[,"SCRAP_YIELD_RATE"])
      RMSE=acc["Test set","RMSE"]
      if(grepl("<",fit_prune1$frame$var[1])){
        ct <- rpart.control(xval=10, minsplit=100, minbucket=100,cp=0.0001) 
        fit1 <- rpart(SCRAP_YIELD_RATE ~ .,data=MODEL_UNIT_DF_SP, control=ct ,method="anova")
        opt<-which.min(fit1$cptable[,"xerror"])
        cp<-fit1$cptable[opt,"CP"]
        fit_prune1<-fit1
        pred<-predict(fit_prune1,newdata = MODEL_UNIT_DF_SP)
        acc<-accuracy(pred,MODEL_UNIT_DF_SP[,"SCRAP_YIELD_RATE"])
        RMSE=acc["Test set","RMSE"]
        save_name<- paste0(gsub(pattern="/",replacement="_", as.character(fit_prune1$frame$var[1])),"_minxerror_",RMSE) 
        if (grepl("<",fit_prune$frame$var[1])){
          save_name<-"leaf"
        }
        else{
          save_name<- paste0(as.character(fit_prune$frame$var[1]),"_minxerror_",RMSE)  
        }
      }else{
        save_name<- paste0(gsub(pattern="/",replacement="_", as.character(fit_prune1$frame$var[1])),"_minxerror_",RMSE) 
        
      }
      save_dir2<-sprintf('%s%s/',save_dir,'result2')
      if(!dir.exists(save_dir2)){
        dir.create(save_dir2,recursive = TRUE)
      }
      list.rules.rpart(fit_prune1,save_name = save_name,dir_name = save_dir2)
      imp_result<-data.frame(colnames=names(fit_prune1$variable.importance),important=fit_prune1$variable.importance)
      setwd(save_dir2)
      write.csv(imp_result,"imp_result_fit_prune.csv",row.names = F)
      #save_name<-"TOM01__SG_SIGN__TDC51_minxerror_0.0229716813461575"
      
      opar<-par(no.readonly = T)
      par(mfrow=c(1,1))
      
      CairoPNG(file = paste0(save_dir,sprintf("tree1_%s%s.png",REC_REVISE_TIME,uuid_data)),width=10000,height=10000,res=1000)
      rpart.plot(fit, shadow.col="gray", box.col="green",  
                 border.col="blue", split.col="red",  
                 split.cex=0.5)
      par(opar)
      dev.off()
      
      
      rule_df<- decision_path(tree_model=fit_prune1,df=MODEL_UNIT_DF_SPWT,save_name,save_path=save_dir2)
      if(save_name!='leaf'){
        #save_name <- "TOM01__SG_SIGN__TDC51D+Z C5_minxerror_0.0229716813461575"
        JIZU<-read.csv(paste(save_dir2,save_name,'.csv',sep=''))
        #JIZU<-read.csv(paste('/apps/R/rgxzl/R_PROJECT/touliao/std/analysis_data/SZ/C502/result2/','TQMTON1__TRIM_FLAG__1_minxerror_0.0123584430250338','.csv',sep=''))
        resultJIZU_Api<-data.frame("WHOLE_BACKLOG_CODE","rule_no","table_name","where","IN_WT_SUM","OUT_WT_SUM","rate")
        var_names<-setdiff(names(JIZU), c("sql", "X", "rule_no" ,"rate","IN_WT_SUM","OUT_WT_SUM"))
        all_names<-colnames(JIZU)
        rule_nos<- nrow(JIZU)
        rule_tag<-1
        for(rule_no in 1:rule_nos){
          rule_temp<-JIZU[rule_no,]
          rule_var<-all_names[!is.na(JIZU[rule_no,])]
          rule_var<-intersect(var_names,rule_var)
          ##表格名字
          tablename<-strsplit(rule_var,"__")
          
          table_len<-length(tablename)
          tablename_un<-c()
          for(len in 1:table_len){
            tablename_un<-c( tablename[[len]][1],tablename_un)
          }
          tablename_un<-unique(tablename_un)
          table_len<-length(tablename_un)
          rule_temp_tag<-1
          print(table_len)
          for(len in 1:table_len){
            tablename_un_len<-tablename_un[len]
            where_temp<- rule_var[grepl(tablename_un_len,rule_var)]
            where_temp1<-''
            print(where_temp)
            if(length(where_temp)>1){
              
              for(i in 1:length(where_temp) ){
                if(any(grepl('substr',rule_temp[,where_temp[i]]))){
                  rule_temp[,where_temp[i]]<-gsub('[^\f\n\r\t\v]*__','substr(',rule_temp[,where_temp[i]])
                  }
                else{
                  rule_temp[,where_temp[i]]<-gsub('[^\f\n\r\t\v]*__','',transform_str(rule_temp[,where_temp[i]],tablename_un_len))
                }
                where_temp1<-ifelse(nchar(where_temp1)==0,rule_temp[,where_temp[i]],paste0(where_temp1,' and ',rule_temp[,where_temp[i]]) ) 
              }
            }
            else{
              if(any(grepl('substr',rule_temp[,where_temp]))){
                rule_temp[,where_temp]<-gsub('[^\f\n\r\t\v]*__','substr(',rule_temp[,where_temp])
              }else{
                rule_temp[,where_temp]<-gsub('[^\f\n\r\t\v]*__','',transform_str(rule_temp[,where_temp],tablename_un_len)) #
              }
              where_temp1<-rule_temp[,where_temp]
            }
            
            where_temp1<-str_replace_all(where_temp1, '&' ,"and")
            where_temp1<-str_replace_all(where_temp1, 'ORDER_UNIT_DIFF' ,"(ORDER_UNIT_MAX_WT-ORDER_UNIT_MIN_WT)")
            ###将字段的NA改为"(trim(字段)!='' or 字段 is not null)"
            if(length(ziduan)!=0){
            for(i in length(ziduan)){
              where_temp1<-str_replace_all(where_temp1,sprintf("%s='NA'",ziduan[i]), sprintf("(trim(%s) ='' or %s is null)",ziduan[i],ziduan[i]))
              where_temp1<-str_replace_all(where_temp1,sprintf("%s!='NA'",ziduan[i]), sprintf("(trim(%s) !='' or %s is not null)",ziduan[i],ziduan[i]) )
            }}
            
            print(tablename_un[len])
            if(rule_temp_tag){
              resultJIZU_temp<-data.frame("WHOLE_BACKLOG_CODE"=WHOLE_BACKLOG_CODE,"rule_no"=rule_no,"table_name"=paste('T_ODS_',tablename_un[len],sep = ''),"where"=where_temp1,"IN_WT_SUM"=rule_temp[,"IN_WT_SUM"],"OUT_WT_SUM"=rule_temp[,"OUT_WT_SUM"],"rate"=rule_temp[,"rate"])
              rule_temp_tag<-0
            }else{
              resultJIZU_temp1<-data.frame("WHOLE_BACKLOG_CODE"=WHOLE_BACKLOG_CODE,"rule_no"=rule_no,"table_name"=paste('T_ODS_',tablename_un[len],sep = ''),"where"=where_temp1,"IN_WT_SUM"=rule_temp[,"IN_WT_SUM"],"OUT_WT_SUM"=rule_temp[,"OUT_WT_SUM"],"rate"=rule_temp[,"rate"])
              resultJIZU_temp<-rbind(resultJIZU_temp,resultJIZU_temp1) #将两表列合并
            }
          }
  
          if(rule_tag){
            resultJIZU_Api<-resultJIZU_temp
            rule_tag=0
          }else{
            resultJIZU_Api<-rbind(resultJIZU_Api,resultJIZU_temp)
          }
        }
        rule_nol<-unique(nchar(resultJIZU_Api$rule_no)) 
        if(length(rule_nol)!=0){
          for(i in 1: length(rule_nol)){
            resultJIZU_Api[nchar(resultJIZU_Api$rule_no)==rule_nol[i],"rule_no"]<-paste0(PRE_UNIT_CODE,substr("0000",1,(4-rule_nol[i])), resultJIZU_Api[nchar(resultJIZU_Api$rule_no)==rule_nol[i],"rule_no"])
          }
        }
        colnames(resultJIZU_Api)<-toupper(names(resultJIZU_Api))
        resultJIZU_Api$RULE_TYPE <- '2'
        resultJIZU_Api$RULE_SEQ_NO <-'0'
        resultJIZU_Api$REC_REVISE_TIME <- REC_REVISE_TIME
        resultJIZU_Api$STD_DEVO_RATE <-1/resultJIZU_Api$RATE
        
        
      }
      else{
        save_dir<-sprintf('%s%s/',save_dir0,WHOLE_BACKLOG_CODE)
        save_dir2<-sprintf('%s%s/',save_dir,'result2')
        if(!dir.exists(save_dir2)){
          dir.create(save_dir2,recursive = TRUE)}
        resultJIZU_Api <- data.frame(WHOLE_BACKLOG_CODE = WHOLE_BACKLOG_CODE,
                                     RULE_NO = '',
                                     TABLE_NAME = '',WHERE = '',
                                     IN_WT_SUM = '',OUT_WT_SUM = '',
                                     RATE ='',RULE_TYPE ='2',RULE_SEQ_NO ='0',
                                     STD_DEVO_RATE = '',
                                     REC_REVISE_TIME=REC_REVISE_TIME)
        
      }
      
      
      
    }
    
    else{
      save_dir<-sprintf('%s%s/',save_dir0,WHOLE_BACKLOG_CODE)
      save_dir2<-sprintf('%s%s/',save_dir,'result2')
      if(!dir.exists(save_dir2)){
        dir.create(save_dir2,recursive = TRUE)}
      resultJIZU_Api <- data.frame(WHOLE_BACKLOG_CODE = WHOLE_BACKLOG_CODE,
                                   RULE_NO = '',
                                   TABLE_NAME = '',WHERE = '',
                                   IN_WT_SUM = '',OUT_WT_SUM = '',
                                   RATE ='',RULE_TYPE ='2',RULE_SEQ_NO ='0',
                                   STD_DEVO_RATE = '',
                                   REC_REVISE_TIME=REC_REVISE_TIME)
      
    }
    print(resultJIZU_Api)
    
    write.csv(resultJIZU_Api,paste(save_dir2,WHOLE_BACKLOG_CODE,'_API.csv',sep=''),row.names = F)
    dbSendUpdate(gxzl, "INSERT INTO gxzl.T_STD_DEVOTE_COEFF_RULE_SUMMARY_RSL VALUES (?,?,?,?,?,?,?,?,?,?)",resultJIZU_Api$WHOLE_BACKLOG_CODE,resultJIZU_Api$RULE_TYPE,resultJIZU_Api$RULE_NO,resultJIZU_Api$RULE_SEQ_NO,resultJIZU_Api$TABLE_NAME,resultJIZU_Api$WHERE,resultJIZU_Api$STD_DEVO_RATE,resultJIZU_Api$IN_WT_SUM,resultJIZU_Api$OUT_WT_SUM,resultJIZU_Api$REC_REVISE_TIME)
    
    
    
    
  }
  
  dbDisconnect(gxzl)
  
}


###当文件名为类似"TOM01__PROD_PLATE_CODE__50/50_minxerror_0.0267990838015214"时，由于中间'/'不能识别其路径，只需把'/'去除，在恰当位置赋给save_name即可（zzyang留）
